//
//  UIViewController-DC.swift
//  NAVPushDemo
//
//  Created by point on 2018/5/12.
//  Copyright © 2018年 whiteboard. All rights reserved.
//

import UIKit
import ObjectiveC

/// 导航返回协议
@objc protocol NavigationProtocol {
    /// 导航将要返回方法
    ///
    /// - Returns: true: 返回上一界面， false: 禁止返回
    @objc optional func navigationShouldPopMethod() -> Bool
}

extension UIViewController: NavigationProtocol {
    func navigationShouldPopMethod() -> Bool {
        return true
    }
}


// MARK:- 页面传值
extension UIViewController {
    
    fileprivate struct OBJC_Key{
        static var dragableKey = 0  //是否已经弹出
        static var dcSourceVcKey = 1 //页面来源
    }
   
    /// 页面传值
    public var dcObjcet: Observable<Any>? {
        get {
            return associatedObject(base: self, key: &objcetKey)
            { return Observable(NSObject()) } // 设置变量的初始值
        }
        set { associateObject(base: self, key: &objcetKey, value:Observable(newValue)) }
    }
    
    
    /// 页面来源
    public var dcSourceVc:String{
        get{
            let sourceS = objc_getAssociatedObject(self, &OBJC_Key.dcSourceVcKey) as? String
            guard let source = sourceS else{
                return "null"
            }
            return source
        }
        set{
            objc_setAssociatedObject(self, &OBJC_Key.dcSourceVcKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }
    
    ///是否已经弹出
    public var alreadyPush :Int{
        get{
            let number = objc_getAssociatedObject(self, &OBJC_Key.dragableKey) as? NSNumber
            guard let num = number else{
                return 0;
            }
            return Int(num.intValue)
        }
        set{
            let number = NSNumber(value: Float(newValue) as Float)
            objc_setAssociatedObject(self, &OBJC_Key.dragableKey, number, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
        }
    }
}

private var catKey: UInt8 = 0
private var objcetKey: UInt8 = 0

func associatedObject<ValueType: AnyObject>(
    base: AnyObject,
    key: UnsafePointer<UInt8>,
    initialiser: () -> ValueType)
    -> ValueType {
        if let associated = objc_getAssociatedObject(base, key)
            as? ValueType { return associated }
        let associated = initialiser()
        objc_setAssociatedObject(base, key, associated,
                                 .OBJC_ASSOCIATION_RETAIN)
        return associated
}

func associateObject<ValueType: AnyObject>(
    base: AnyObject,
    key: UnsafePointer<UInt8>,
    value: ValueType) {
    objc_setAssociatedObject(base, key, value,
                             .OBJC_ASSOCIATION_RETAIN)
}
